package databaseManager.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 
 * Un semplice oggetto che gestisce una connessione, utilizzando il driver
 * MYSQL.
 * 
 * @author Nicola
 * 
 */
public class ConnectionManager implements IConnection{

	// JDBC driver di esempio
	static final String JDBC_DRIVER = "jdbc:mysql:";
	static final String JDBC_FORNAME = "com.mysql.jdbc.Driver";
	// jdbc:mysql://localhost/feedback?"+ "user=sqluser&password=sqluserpw"

	// Parametri della connessione
	private String db_url = "dburl_not_set";
	private String db_name = "dbname_not_set";
	private String user = "user_not_set";
	private String pass = "password_not_set";

	// Connessione
	private Connection conn;

	public ConnectionManager(String db_url, String db_name, String user,
			String pass) {
		super();
		this.db_url = db_url;
		this.user = user;
		this.user = pass;
		this.db_name = db_name;
	}

	public ConnectionManager() {
		super();
		setRoot();
	}

	// Getters and Setters
	public String getDb_url() {
		return db_url;
	}

	public void setDb_url(String db_url) {
		this.db_url = db_url;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String password) {
		this.pass = password;
	}

	public void setDb_name(String db_name) {
		this.db_name = db_name;
	}

	public void connect() {

		try {
			Class.forName(JDBC_FORNAME);
			conn = DriverManager
					.getConnection("jdbc:mysql://localhost:3306/"+db_name+"?user="+user+"&password="+pass);
		} catch (SQLException se) {
			// Handle errors for JDBC
			se.printStackTrace();
		} catch (Exception e) {
			// Handle errors for Class.forName
			e.printStackTrace();

		}

	}

	/**
	 * Setta i dati di manipolazione del database web_activity_manager
	 */
	private void setRoot() {
		this.user = "manipulator";
		this.pass = "qwerty";
		this.db_url = "localhost:3306";
		this.db_name = "web_activity_manager";
	}

	public Connection getConnection() {
		return conn;
	}

	public void unConnect() {

		try {
			Class.forName(JDBC_DRIVER);
			conn.close();
		} catch (SQLException se) {
			// Handle errors for JDBC
			se.printStackTrace();
		} catch (Exception e) {
			// Handle errors for Class.forName
			e.printStackTrace();

		}

	}

}
